//
//  JYListController.m
//  JYShop
//
//  Created by 花花 on 2017/9/28.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYListController.h"
#import "JYSearchBar.h"
#import "JYSearchViewController.h"
#import "JYFunView.h"
#import "JYFunModel.h"
#import <MJRefresh/MJRefresh.h>

#import "JYPublicCell.h"
#import "JYShopCell.h"
#import "JYListModel.h"
#import "JYShowView.h"
#import "JYHomeViewModel.h"
#import "PurchaseCarAnimationTool.h"
#import "JYEmptyView.h"

@interface JYListController ()<UITableViewDataSource,UITableViewDelegate>

//搜索
@property(nonatomic) JYSearchBar *searchBar;

//collectionView 新鲜蔬菜 肉禽蛋类 时令水果 酒水饮料 水产冻货
@property (nonatomic, strong) JYFunView *funView;

@property(nonatomic,strong)NSMutableArray *dataArr;

@property(nonatomic) JYHomeViewModel *viewModel; //数据请求
@property(nonatomic,strong)NSMutableArray *categorysArr;


@property(nonatomic,strong)NSMutableArray *depositObjArr;


@end

static NSString  *const ListCellID = @"ListCellID";
@implementation JYListController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupRefresh];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setupSubView];
    [self setupTableView];
    
    [self loadDataFromNetwork];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)setupRefresh{

    JYWeakSelf;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDataFromNetwork];
    }];

}

- (void)loadDataFromNetwork{
    [self.tableView.mj_header endRefreshing];
    
    
    [self.categorysArr removeAllObjects];
    
    [self.dataArr removeAllObjects];
    
    
    //fun数据包括左边数据
    [self.viewModel  handlerCategoryDataWithSuccess:^(NSArray *categorysArr) {
        
        for (NSDictionary *dic in categorysArr) {
            
            JYCategorysModel *model = [JYCategorysModel mj_objectWithKeyValues:dic];
            [self.categorysArr addObject:model];
        }
        self.funView.dataArr = self.categorysArr;
        
    }];
    
    [HTTPRequest POST:kCommonUserGreensListUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {
        
        if (SUCCESS) {
            [self.dataArr removeAllObjects];
            [self.depositObjArr removeAllObjects];
            
            self.dataArr = [JYListModel mj_objectArrayWithKeyValuesArray:resposeObject[@"data"]];
            
            for (NSDictionary *dic in resposeObject[@"data"]) {
                
                if (![dic[@"depositObj"] isKindOfClass:[NSNull class]]) {
              
                      self.depositObjArr = [JYDepositObjModel mj_objectArrayWithKeyValuesArray:dic[@"depositObj"]];
                }else{
                
                    NSLog(@"depositObj为空");
                }
            }
            [self.tableView reloadData];
            
        }else if ([resposeObject[@"result"] integerValue] == 14){
            
            [self.dataArr removeAllObjects];
            
            [self.tableView reloadData];
            
            
        }else{
        
        [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
          self.currentPageStatus = PageStatusSucceed;
    } failure:^(NSError *error) {
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];

    }];
}
- (void)pullDownRefresh:(int)page{

    [self loadDataFromNetwork];

}
- (void)setupSubView{

    JYWeakSelf;
    
    
    _searchBar = [[JYSearchBar alloc]initWithOffSet:10];
    _searchBar.bgView.alpha= 1;
    _searchBar.backgroundColor = [UIColor whiteColor];
    _searchBar.searchBarClickCallBack = ^{
        JYSearchViewController *searchVc = [JYSearchViewController new];
        
        [weakSelf.navigationController pushViewController:searchVc animated:YES];
    };
   
    _searchBar.frame = CGRectMake(0, 0, Screen_Width, 64);
    
     [self.view addSubview:_searchBar];
    
}

- (void)setupTableView{
    
    self.tableView.rowHeight = 100;
    
    self.tableView.backgroundColor = kBgColor;
    self.tableView.height = Screen_Height-49;
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);

    [self.tableView registerNib:[UINib nibWithNibName:@"JYPublicCell" bundle:nil] forCellReuseIdentifier:ListCellID];
    
    self.tableView.tableHeaderView = self.funView;
    self.tableView.tableFooterView = [UIView new];
    

    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    JYPublicCell *cell = [tableView dequeueReusableCellWithIdentifier:ListCellID];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.listModel = [self.dataArr safeObjectAtIndex:indexPath.row];
    JYWeakSelf;
    cell.ShopCountEditBlock = ^(NSInteger count,UIImageView *imgeView){
        
        [weakSelf addUserShopCartIndexPath:indexPath count:count];
        
        
        CGRect rect = [weakSelf.tableView rectForRowAtIndexPath:indexPath];
        
        
        rect.origin.y = rect.origin.y - [weakSelf.tableView contentOffset].y;
        CGRect imageViewRect = imgeView.frame;
        imageViewRect.origin.y = rect.origin.y+imageViewRect.origin.y;
        [[PurchaseCarAnimationTool shareTool]startAnimationandView:imgeView andRect:imageViewRect andFinisnRect:CGPointMake(ScreenWidth/4 *2.5, ScreenHeight-49) andFinishBlock:^(BOOL finish) {
            UIView *tabbarBtn = weakSelf.tabBarController.tabBar.subviews[3];
            [PurchaseCarAnimationTool shakeAnimation:tabbarBtn];
            
            [weakSelf GoodCarTotalCountFormNetwork];
        }];
        
        
        
        [tableView reloadData];
        
        
    };
    
    return cell;
    
}


- (void)GoodCarTotalCountFormNetwork{
    

    [HTTPRequest POST:kUserShoppingTrolleyGoodsTotalUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {
        JYWeakSelf;
        if (SUCCESS) {
            int totalCount = [resposeObject[@"data"] intValue];
            
            NSLog(@"购物车数量: %d",totalCount);
            if (totalCount>0) {
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",totalCount];
                
            }else{
                
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = nil;
            }
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
        
    } failure:^(NSError *error) {
        
//          [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
    }];
    
    
}
- (void)addUserShopCartIndexPath:(NSIndexPath *)indexPath count:(NSInteger)count{


    JYListModel *productModel =[self.dataArr safeObjectAtIndex:indexPath.row];
    
    if (count <= 0) {
        count = 1;
    } else  if (count > 10000) {
        count = productModel.goodsAmount;
    }
    //根据请求结果决定是否改变数据
    productModel.goodsAmount = count;
    
    
    [self adduserShoppingTrolleyListIndexPath:indexPath count:count];

}

- (void)adduserShoppingTrolleyListIndexPath:(NSIndexPath *)indexPath count:(NSInteger)count{

   JYListModel *productModel =[self.dataArr safeObjectAtIndex:indexPath.row];
    
    JYDepositObjModel *model = [self.depositObjArr safeObjectAtIndex:indexPath.row];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSMutableArray *listArr = [NSMutableArray array];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"goodsAmount"] = @(productModel.goodsAmount);
    dic[@"goodsId"]  = productModel.goodsId;
    dic[@"goodsName"] = productModel.goodsName;
    dic[@"goodsPictureUrl"] = productModel.goodsPictureUrl;
    dic[@"goodsPrice"]  = productModel.goodsPrice;
    dic[@"originalprice"] = productModel.originalprice;
    dic[@"unit"] = productModel.unit;
    dic[@"userId"] = LH.userId;
    dic[@"categroyId"] = productModel.categroyId;
    
    if (model.goodsName == nil && model.goodsPrice == nil &&  model.goodsPictureUrl == nil && model.unit == nil) {
        
        NSLog(@"都为空表示无押金商品");
    }else{
        NSLog(@"有-有-有押金商品");
        NSMutableArray *depositObj = [NSMutableArray array];
        NSMutableDictionary *dic1 = [NSMutableDictionary dictionary];
        dic1[@"goodsId"] = model.goodsId;
        dic1[@"goodsName"] = model.goodsName;
        dic1[@"goodsPrice"] = model.goodsPrice;
        dic1[@"goodsPictureUrl"]  = model.goodsPictureUrl;
        dic1[@"goodsAmount"] = model.goodsAmount;
        dic1[@"unit"] = model.unit;
        [depositObj addObject:dic1];
        [dic setObject:depositObj forKey:@"depositObj"];
    }
    [listArr addObject:dic];
    
    [param setValue:listArr forKey:@"list"];

    [HTTPRequest POST:kAdduserShoppingTrolleyUrl parameter:param success:^(id resposeObject) {
        
           [[NSNotificationCenter defaultCenter]postNotificationName:kCountChangeNotification object:nil];
        NSLog(@"添加商品到购物车 %@",resposeObject);
        if (SUCCESS) {
            
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kCountChangeNotification object:nil];
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        }
        
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
        
    }];
    


}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 10;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    
    for (UIView * sv in cell.subviews) {
        
        if ([sv isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")]) {
            JYWeakSelf;
            JYShowView *showView = [[JYShowView alloc]initWithFrame:CGRectMake(0, 0, showView_Width, showView_Height) isSected:YES alertMessage:@"删除后商品将不在显示，确认删除类商品吗?" btnHandler:^(JYShowType type) {
                if (type == JYShowTypeCancel) {
                    
                }else{
                    [weakSelf loadDeleteAtIndexPath:indexPath];
                }
            }];
            [showView show];
            
        }
    }
}

- (void)loadDeleteAtIndexPath:(NSIndexPath *)indexPath{
    
    JYListModel *model = [self.dataArr safeObjectAtIndex:indexPath.row];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = LH.userId;
    param[@"goodsId"] = model.goodsId;
    param[@"getDeletCommonUserOrderType"] = @(0);//0默认删除单个 1 全删 2批量
    param[@"categroyId"] = model.categroyId;
    

    [HTTPRequest POST:kDeleteCommonUserGreensUrl parameter:param success:^(id resposeObject) {
        if (SUCCESS) {
            
            [self.dataArr removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kHomeCountChangeNotification object:nil];
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
    } failure:^(NSError *error) {
        
        
        [MBProgressHUD LY_ShowError:(kNoNetworkTips) time:2.0];
    }];
}

- (void)loadfunDataCategoryId:(NSString *)categoryId{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = LH.userId;
    param[@"categroyId"] = categoryId;
    
    [HTTPRequest POST:kCommonUserGreensListUrl parameter:param success:^(id resposeObject) {
       
        if (SUCCESS) {
            
            [self.tableView reloadData];
        }else{
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
    }];

}
- (JYFunView *)funView{
    
    if (!_funView) {
        _funView = [[JYFunView alloc]initWithFrame:CGRectMake(0,1, Screen_Width, funHight)];
        _funView.FunDidSelectItemAtIndexPath = ^(NSArray *arr){
            NSString *categoryId = nil;
            
            for (NSDictionary  *dic in arr) {
                
                JYListModel *model = [JYListModel mj_objectWithKeyValues:dic];
                
                categoryId = model.id;
            }
            NSLog(@"funcation %@",categoryId);
           
        };
    }
    return _funView;
}
- (NSMutableArray *)dataArr{

    if (!_dataArr ) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;

}
- (JYHomeViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel =[[JYHomeViewModel alloc]init];
        
    }
    return _viewModel;
}
- (NSMutableArray *)categorysArr{
    if (!_categorysArr) {
        _categorysArr =[NSMutableArray array];
    }
    return _categorysArr;
    
}
- (NSMutableArray *)depositObjArr{
    
    if (!_depositObjArr) {
        _depositObjArr = [NSMutableArray array];
    }
    
    return _depositObjArr;
    
    
}

@end
